package com.example.newsapp.activity;


import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.newsapp.utils.DBHelper;
import com.example.newsapp.R;
import com.example.newsapp.adapter.NewsAdapter;
import com.example.newsapp.model.UserNewsItem;
import com.example.newsapp.utils.UserSessionUtil;

import java.util.List;

public class HistoryActivity extends AppCompatActivity {

    private RecyclerView historyRecyclerView;
    private NewsAdapter adapter;
    private List<UserNewsItem> historyList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);
        Toolbar toolbar = findViewById(R.id.menuToolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        toolbar.setNavigationOnClickListener(v -> finish());

        historyRecyclerView = findViewById(R.id.historyRecyclerView);
        historyRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        DBHelper dbHelper = new DBHelper(this);
        try {
            historyList = dbHelper.getHistoryByUser(UserSessionUtil.getUserId(this));
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "加载历史记录失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }


        // 2. 设置适配器
        adapter = new NewsAdapter(historyList);
        historyRecyclerView.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_history, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.action_clear_history) {
            showClearHistoryDialog();  // 点击后弹出确认框
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showClearHistoryDialog() {
        new AlertDialog.Builder(this)
                .setTitle("确认清空？")
                .setMessage("确定要清空所有浏览记录吗？")
                .setPositiveButton("清空", (dialog, which) -> {
                    DBHelper dbHelper = new DBHelper(this);
                    dbHelper.clearHistoryByUser(UserSessionUtil.getUserId(this));
                    historyList.clear();
                    adapter.notifyDataSetChanged();
                    Toast.makeText(this, "浏览记录已清空", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }


}
